<?php

declare(strict_types=1);

namespace app\api\controller\project;

use app\BaseController;


use app\common\model\Project\Project as ProjectModel;
use app\common\model\Project\Order as OrderModel;
use app\common\model\User\User as UserModel;
use app\common\model\User\Record as RecordModel;
use app\common\model\User\Address as AddressModel;
use app\common\validate\Project\Order as OrderValidate;
use app\common\validate\User\Record as RecordValidate;
use think\exception\ValidateException;


class Project extends BaseController
{

    public function initialize()

    {
        parent::initialize();

        $this->ProjectModel = new ProjectModel();
        $this->OrderModel = new OrderModel();
        $this->UserModel = new UserModel();
        $this->AddressModel = new AddressModel();
        $this->RecordModel = new RecordModel();
    }

    // 添加预约订单
    public function add()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $addrid = $this->request->param('addrid', 0);
            $projectid = $this->request->param('projectid', 0);
            $createtime = $this->request->param('createtime', '');
            $content = $this->request->param('content', '');

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if (!$userinfo) {
                $this->error('用户不存在');
                exit;
            }

            //用户的收货地址
            $address = $this->AddressModel->find($addrid);

            if (!$address) {
                $this->error('收货地址不存在');
                exit;
            }

            //判断这个收货地址是不是这个用户的
            if ($address['userid'] != $userid) {
                $this->error('非法选择上门地址');
                exit;
            }

            //判断服务选项是否存在
            $project = $this->ProjectModel->find($projectid);

            if (!$project) {
                $this->error('预约的服务不存在，请重新选择');
                exit;
            }

            //将毫秒转换为秒
            $createtime = $createtime / 1000;

            //判断是否是否为过期的时间
            $now = time() + 3600 * 6;
            if ($now > $createtime) {
                $this->error('请选择有效时间,在当前时间的6个小时后预约');
                exit;
            }

            $data = [
                'userid' => $userid,
                'addrid' => $addrid,
                'projectid' => $projectid,
                'content' => $content,
                'status' => 0,
                'createtime' => $createtime
            ];

            try {
                validate(OrderValidate::class)->check($data);
                $result = $this->OrderModel->save($data);
            } catch (ValidateException $e) {
                // 捕获异常
                $this->error($e->getError());
                exit;
            }


            if ($result === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('预约成功，请等待客服联系', '/pages/project/index');
                exit;
            }
        }
    }

    // 预约列表
    public function index()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $status = $this->request->param('status', '');

            $where = [];
            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if (!$userinfo) {
                $this->error('用户不存在');
                exit;
            }

            $where['userid'] = $userid;

            if ($status == '0' || !empty($status)) {
                $where['status'] = $status;
            }



            $result = $this->OrderModel->withJoin(['project'], 'LEFT')->where($where)->order('id', 'DESC')->select();
            // echo $this->OrderModel->getlastsql();exit;


            if ($result === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('', '', $result);
                exit;
            }
        }
    }

    // 支付
    public function pay()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $id = $this->request->param('id', 0);

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if (!$userinfo) {
                $this->error('用户不存在');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if (!$orderinfo) {
                $this->error('预约订单不存在，请重新下单');
                exit;
            }

            if ($orderinfo['status'] != '1') {
                $this->error('预约已经付款，不需要重复付款');
                exit;
            }

            $point = $userinfo['point'];

            // 判断用户积分够不够
            $UpdatePoint = bcsub((string)$point, $orderinfo['price']);

            if ($UpdatePoint < 0) {

                $this->error('积分不足，请充值后操作');
                exit;
            }

            // 开启事条
            //预约订单表(update) 用户积分(update) 消费记录(insert)
            $this->OrderModel->startTrans();
            $this->UserModel->startTrans();
            $this->RecordModel->startTrans();

            //组装订单表数据
            $orderdata = [
                'id' => $id,
                'status' => 2
            ];

            //预约订单表
            $OrderStatus = $this->OrderModel->update($orderdata);


            if ($OrderStatus === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            }

            // 用户积分
            $UserStatus = $this->UserModel->update(['id' => $userid, 'point' => $UpdatePoint]);

            if ($UserStatus === FALSE) {
                //回滚
                $this->OrderModel->rollback();
                $this->error($this->UserModel->getError());
                exit;
            }

            // 消费记录
            $RecordData = [
                'point' => $orderinfo['price'],
                'content' => "预约订单的---消费的积分为：" . $orderinfo['price'],
                'state' => 6,
                'userid' => $userid
            ];

            // 插入消费记录表

            try {
                validate(RecordValidate::class)->check($RecordData);

                $RecordStatus = $this->RecordModel->save($RecordData);
            } catch (ValidateException $e) {
                // 捕获异常
                $this->error($e->getError());
                exit;
            }


            if ($RecordStatus === FALSE) {
                //回滚
                $this->UserModel->rollback();
                $this->OrderModel->rollback();
                $this->error($this->RecordModel->getError());
                exit;
            }

            if ($OrderStatus !== FALSE &&  $UserStatus !== FALSE && $RecordStatus !== FALSE) {
                //提交事务
                $this->OrderModel->commit();
                $this->UserModel->commit();
                $this->RecordModel->commit();
                $this->success('付款成功');
                exit;
            } else {
                //回滚
                $this->RecordModel->rollback();
                $this->UserModel->rollback();
                $this->OrderModel->rollback();
                $this->error('付款失败,请重新操作');
                exit;
            }
        }
    }

    // 详情
    public function info()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $id = $this->request->param('id', 0);

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if (!$userinfo) {
                $this->error('用户不存在');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if (!$orderinfo) {
                $this->error('预约订单不存在，请重新下单');
                exit;
            }


            //预约订单详情  alias用于设置当前数据表的别名
            $result = $this->OrderModel->alias("order")->with('project')->where(['order.id' => $id])->find();


            if ($result === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('', '', $result);
                exit;
            }
        }
    }

    // 确认收货
    public function receiving()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $id = $this->request->param('id', 0);

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if (!$userinfo) {
                $this->error('用户不存在');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if (!$orderinfo) {
                $this->error('预约订单不存在，请重新下单');
                exit;
            }

            //组装订单表数据
            $orderdata = [
                'id' => $id,
                'status' => 3
            ];

            //预约订单表
            $result = $this->OrderModel->update($orderdata);

            if ($result === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('确认收货成功', '', '');
                exit;
            }
        }
    }

    // 评分
    public function rate()
    {
        if ($this->request->isPost()) {

            $userid = $this->request->param('userid', 0);
            $id = $this->request->param('id', 0);
            $rate = $this->request->param('rate', 0);

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if (!$userinfo) {
                $this->error('用户不存在');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if (!$orderinfo) {
                $this->error('预约订单不存在，请重新下单');
                exit;
            }

            $data = [
                'id' => $id,
                'rate' => $rate,
                'status' => 3
            ];

            //评分
            $result = $this->OrderModel->update($data);


            if ($result === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('预约订单评价成功', '', '');
                exit;
            }
        }
    }

    // 撤销预约申请中
    public function revoke()
    {
        if ($this->request->isPost()) {
            $userid = $this->request->param('userid', 0);
            $id = $this->request->param('id', 0);

            //判断用户是否存在
            $userinfo = $this->UserModel->find($userid);

            if (!$userinfo) {
                $this->error('用户不存在');
                exit;
            }

            $orderinfo = $this->OrderModel->find($id);

            if (!$orderinfo) {
                $this->error('预约订单不存在，请重新下单');
                exit;
            }

            $data = [
                'id' => $id,
                'status' => -2
            ];

            //预约订单表
            $result = $this->OrderModel->update($data);

            if ($result === FALSE) {
                $this->error($this->OrderModel->getError());
                exit;
            } else {
                $this->success('撤销预约订单成功，请等待后台审核', '', null);
                exit;
            }
        }
    }
}
